package top.waikin.mooc.admin.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.waikin.mooc.admin.domain.RoleDto;
import top.waikin.mooc.admin.service.RoleService;
import top.waikin.mooc.common.api.CommonResult;
import top.waikin.mooc.entity.Role;

import java.util.List;

/**
 * 后台用户角色 前端控制器
 */
@RestController
@RequestMapping("/role")
@Api(tags = "RoleController", description = "角色管理")
public class RoleController {
    @Autowired
    RoleService roleService;

    @ApiOperation("创建角色")
    @PostMapping
    public CommonResult<Integer> create(@RequestBody @Validated RoleDto roleDto) {
        int id = roleService.create(roleDto);
        return CommonResult.success(id);
    }

    @ApiOperation("删除角色")
    @DeleteMapping("/{id}")
    public CommonResult delete(@PathVariable Integer id) {
        boolean b = roleService.removeById(id);
        return CommonResult.decide(b);
    }

    @ApiOperation("修改角色")
    @PutMapping("/{id}")
    public CommonResult update(@PathVariable Integer id, @RequestBody @Validated RoleDto roleDto) {
        boolean b = roleService.update(id, roleDto);
        return CommonResult.decide(b);
    }

    @ApiOperation("获取角色")
    @GetMapping("/{id}")
    public CommonResult<Role> getById(@PathVariable Integer id) {
        Role role = roleService.getById(id);
        return CommonResult.success(role);
    }

    @ApiOperation("获取角色列表")
    @GetMapping
    public CommonResult<List<Role>> getAll() {
        List<Role> roleList = roleService.list();
        return CommonResult.success(roleList);
    }

    @ApiOperation("给角色分配权限")
    @PostMapping("/{id}/permission")
    public CommonResult updatePermission(@PathVariable Integer id,
                                         @RequestParam List<Integer> permissionIds) {
        boolean b = roleService.updatePermission(id, permissionIds);
        return CommonResult.decide(b);
    }

}
